﻿# encoding=utf-8
import sys
import os
import telnetlib
from time import sleep
import threading

# 配置选项  
HOST = 'nas.chenqiuheng.top' # Telnet服务器IP  
USERNAME = 'admin'   # 登录用户名  
PASSWORD = '271243712'  # 登录密码  
PORT = 23
TIMEOUT = 10
FINISH = '$ '      # 命令提示符  
COMMANDS = ['echo "test"']  
    
class UeTelnet():
    def __init__(self, _host, _username, _password, _port, _timeout):
        self.host = _host
        self.username = _username
        self.password = _password
        self.port = _port
        self.timeout = _timeout

    def Connect(self):
        try:
            print "Connecting"
            self.telnetob = telnetlib.Telnet(self.host, port=self.port, timeout=self.timeout)  
            self.telnetob.set_debuglevel(0)
            if not self.username == "": # 如果没有填写用户名则按照没有验证来登录
                return self.UserLogin()
            else:
                print "user is null, no encryption"
                if self.telnetob.read_until(FINISH):
                    return 1
        except Exception,e:
            print e.message
            self.telnetob.close()
            print "total:",threading.enumerate()
            
    def UserLogin(self):
        # 输入登录用户名
        self.telnetob.read_until('login: ')
        self.telnetob.write(self.username + '\n')
        # 输入登录密码
        self.telnetob.read_until('Password: ')
        self.telnetob.write(self.password + '\n')
        # 判断是否登录成功,出现$标志，证明登录成功，否则失败
        # 6s的超时，验证失败将抛出异常
        time = threading.Timer(5, self.RaiseErro, args=("****** login incorrect!\n",))
        time.start()
        if self.telnetob.read_until(FINISH):
            print "login successful"
            time.cancel()
            return 1

    def RaiseErro(self, erro):
        raise RuntimeError(erro)

    def DoAction(self, commands):
        # 登录完毕后执行命令
        for command in commands:
            self.telnetob.write('%s\n' % command)
            print "cmd"
            print self.telnetob.read_until(FINISH)


if __name__=='__main__':  
    ueTelent = UeTelnet(HOST, USERNAME, PASSWORD, PORT, TIMEOUT)
    if (ueTelent.Connect() == 1):
        print "start cmd"
        while(1):
            ueTelent.DoAction(COMMANDS)
            sleep(1)
        